package com.db.patterns.server;

import java.util.ArrayList;
import java.util.List;

import cm.db.patterns.commands.UpdateCommand;

import com.db.patterns.caches.Cache;

public class PublishCache implements Cache {

	private Cache cache;
	List<CacheListener> listeners = new ArrayList<>();
	
	public PublishCache(Cache cache) {
		this.cache = cache;
	}
	
	public void addListener(CacheListener listener) {
		listeners.add(listener);
	}
	
	public void removeListener(CacheListener listener) {
		listeners.remove(listener);
	}
	
	@Override
	public Object get(String key) {
		return cache.get(key);
	}

	@Override
	public void put(String key, Object value) {
		cache.put(key, value);
		notifyListeners(key, value);
	}
	
	private void notifyListeners(String key, Object value) {
		for (CacheListener listener : listeners) 
			listener.update(new UpdateCommand(key, value));
	}
	
	public void stop() {
		listeners.clear();
	}

}
